"""
    panel player
"""
import wx
import control_player
import track
import menus
import data
from data import *


class playlist(wx.BoxSizer):
    def __init__(self, parent):
        self.parent = parent
        wx.BoxSizer.__init__(self, wx.VERTICAL)
        
        self.musicdata = [['Gustavo Cerati','Verbo Carne'],['Enrique Bunbury','Alicia']]
        
        self.panel_player = control_player.control_player(self.parent)
        self.panel_control = wx.BoxSizer(wx.HORIZONTAL)
        self.panel_1 = wx.Panel(self.parent, -1)
        self.panel_track = track.track(self.parent)
        
        self.list = wx.ListCtrl(self.parent, -1, style=wx.LC_REPORT|wx.SUNKEN_BORDER)
        self.bt_playlist_add = wx.BitmapButton(self.parent, -1, wx.Bitmap(player_images["add"], wx.BITMAP_TYPE_ANY))
        self.bt_playlist_remove = wx.BitmapButton(self.parent, -1, wx.Bitmap(player_images["remove"], wx.BITMAP_TYPE_ANY))        
        self.bt_playlist_options = wx.BitmapButton(self.parent, -1, wx.Bitmap(player_images["options"], wx.BITMAP_TYPE_ANY))
        self.bt_playlist_menu = wx.BitmapButton(self.parent, -1, wx.Bitmap(player_images["list"], wx.BITMAP_TYPE_ANY))        
    
        self.pos = None
        
        self.__set_properties()
        self.__do_layout()
        self.__set_actions()
        
        
        self.track_select = None
    def __set_properties(self):
        self.list.SetMinSize((450, 500))
        self.list.InsertColumn(0, "ID", wx.LIST_FORMAT_RIGHT, 40)
        self.list.InsertColumn(1, "Artist", wx.LIST_FORMAT_LEFT, 100)
        self.list.InsertColumn(2, "Title", wx.LIST_FORMAT_LEFT, 200)
        self.list.InsertColumn(3, "Album", wx.LIST_FORMAT_LEFT, 200)
        
        self.bt_playlist_add.SetSize(self.bt_playlist_add.GetBestSize())
        self.bt_playlist_remove.SetSize(self.bt_playlist_remove.GetBestSize())
        self.bt_playlist_options.SetSize(self.bt_playlist_options.GetBestSize())
        self.bt_playlist_menu.SetSize(self.bt_playlist_menu.GetBestSize())
        
    def __do_layout(self):
        self.Add(self.panel_player, 0, 0, 0)
        self.Add(self.panel_track, 1, wx.EXPAND, 0)
        self.Add(self.list, 0, 0, 0)
                
        self.panel_control.Add(self.bt_playlist_add, 0, 0, 0)
        self.panel_control.Add(self.bt_playlist_remove, 0, 0, 0)
        self.panel_control.Add(self.panel_1, 1, wx.EXPAND, 0)
        self.panel_control.Add(self.bt_playlist_options, 0, 0, 0)
        self.panel_control.Add(self.bt_playlist_menu, 0, 0, 0)
        
        self.Add(self.panel_control, 0, wx.EXPAND|wx.ALIGN_RIGHT, 0)
    
    def __set_actions(self):
        #self.parent.Bind(wx.EVT_LIST_ITEM_SELECTED, self.handler_playlist_selected, self.list)
        self.parent.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.handler_playlist_activated, self.list)
        #self.parent.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.handler_playlist_clickright, self.list)
        self.parent.Bind(wx.EVT_BUTTON, self.handler_playlist_add, self.bt_playlist_add)
        self.parent.Bind(wx.EVT_BUTTON, self.handler_playlist_remove, self.bt_playlist_remove)
        self.parent.Bind(wx.EVT_BUTTON, self.handler_playlist_options, self.bt_playlist_options)
        self.parent.Bind(wx.EVT_BUTTON, self.handler_playlist_menu, self.bt_playlist_menu)
    
    def playlist_changed(self, result):
        new_track = result.value()
        print "changelist:",new_track
        if new_track['type']==0: #add
            self.addTrackToPlaylist(int(new_track['id']))
        if new_track['type']==2: #shuffle
            self.list.DeleteAllItems()
            self.playlist_generate()
        elif new_track['type']==3: #remove
            self.removeTrackToPlaylist(new_track['position'])
        elif new_track['type']==4: #clear
            self.list.DeleteAllItems()
        elif new_track['type']==5: #change positions
            #self.list.DeleteAllItems()
            #self.playlist_generate()
            self.pos = new_track['newposition']
            self.list.DeleteItem(new_track['position'])
            self.addTrackToPlaylist(int(new_track['id']))
    
    def handler_playlist_activated(self, event): # wxGlade: MyFrame.<event_handler>
        self.parent.Angel.playlist_set_next(int(self.list.GetFirstSelected()))
        self.parent.Angel.playback_tickle()
        if self.parent.status == 0 or self.parent.status == 2:
            self.parent.Angel.playback_start()
        event.Skip()
        
    def handler_playlist_selected(self, event): # wxGlade: MyFrame.<event_handler>
        event.Skip()

    def handler_playlist_clickright(self, event): # wxGlade: MyFrame.<event_handler>
        print "click derecho"
        event.Skip()

    def handler_playlist_add(self, event): # wxGlade: MyFrame.<event_handler>
        menuAdd = wx.Menu()
        addfilesid = wx.NewId()
        self.parent.Bind(wx.EVT_MENU, self.Action_AddFiles, id=addfilesid)
        menuAdd.Append(addfilesid,"Agregar")
        
        self.parent.PopupMenu(menuAdd)
        menuAdd.Destroy()
        
    def Action_AddFiles(self, event):
        print "paso por aqui"
    
    def handler_menu_add(self, event):
        print "ok"
        
    def handler_menu_remove(self, event):
        print ""
        
    def handler_playlist_remove(self, event): # wxGlade: MyFrame.<event_handler>
        print "Event handler `handler_playlist_remove' not implemented!"
        event.Skip()

    def handler_playlist_options(self, event): # wxGlade: MyFrame.<event_handler>
        print "Event handler `handler_playlist_options' not implemented!"
        event.Skip()

    def handler_playlist_menu(self, event): # wxGlade: MyFrame.<event_handler>
        print "Event handler `handler_playlist_menu' not implemented!"
        event.Skip()
    
    def playlist_generate(self):
        self.parent.Angel.playlist_list_entries('_active', self.__getTracks)
    
    def set_track(self, result):
        self.parent.Angel.medialib_get_info(result.value(), self.__setTrack)
        
    def __setTrack(self, result):
        track = self.__getTagInfo(result.value())
        self.panel_track.setTrack(track)
        self.select_item(track[0])
        
    
    def __getTracks(self, result):
        list = result.value()
        
        for id in list:
            self.addTrackToPlaylist(id)
    
    def select_item(self, id):
        for i in range(self.list.GetItemCount()):
            if int(id) == int(self.list.GetItem(i).GetText()):
                if self.track_select is not None:
                    self.list.Select(self.track_select,0)
                self.list.Select(i,1)
                self.track_select = i
                return 
    
    def __getTagInfo(self, info):
        track = []
        track.append(info['id'])
        
        if info.has_key('artist'):
            track.append(info["artist"])
        else:
            track.append("No artist")
            
        if info.has_key('title'):
            track.append(info["title"])
        else:
            track.append(data.filename(info['url']))
        
        if info.has_key('album'):
            track.append(info["album"])
        else:
            track.append("")
            
        return track
    
    def addTrackToPlaylist(self, id):
        self.parent.Angel.medialib_get_info(id, self.__addTrackToPlaylist)

    
    def __addTrackToPlaylist(self, result):
        if self.pos is None:
            self.list.Append(self.__getTagInfo(result.value()))
        else:
            track = self.__getTagInfo(result.value())
            self.list.InsertStringItem(self.pos,str(track[0]))
            self.list.SetStringItem(self.pos,1,track[1])
            self.list.SetStringItem(self.pos,2,track[2])
            self.list.SetStringItem(self.pos,3,track[3])
            self.pos = None
    
    
    def removeTrackToPlaylist(self, position):
        self.list.DeleteItem(position)
    
    def setStatus(self, result):
        if result.iserror():
            self.parent.myerror()
        else:
            self.parent.status = result.value()
    
    def setPlayTimeTrack(self):
        self.parent.Angel.signal_playback_playtime(self.__setPlayTimeTrack)
        return True
    
    def __setPlayTimeTrack(self, result):
        total = result.value()
        min = total/(60*1000)
        sec = (total - min*1000*60)/1000
        
        if len(str(min))==1: min = "0%s" % min
        if len(str(sec))==1: sec = "0%s" % sec
        
        self.panel_track.setPlayTime(min, sec)
        

